<?php

/**
 * This is the model class for table "chapters".
 *
 * The followings are the available columns in table 'chapters':
 * @property integer $id
 * @property integer $mangaId
 * @property integer $volume
 * @property integer $sequence
 * @property integer $subSequence
 * @property string $title
 * @property string $createdAt
 * @property string $updatedAt
 */
class Chapter extends ActiveRecord {

	public $cover;

	/**
	 * Returns the static model of the specified AR class.
	 * @param string $className active record class name.
	 * @return Chapter the static model class
	 */
	public static function model($className = __CLASS__) {
		return parent::model($className);
	}

	/**
	 * @return string the associated database table name
	 */
	public function tableName() {
		return 'chapters';
	}

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules() {
		return array(
			array(
				'mangaId, volume, sequence',
				'numerical',
				'integerOnly'=>true
			),
			array('subSequence', 'length', 'max'=>1),
			array('title', 'length', 'max'=>255),
			array(
				'cover',
				'EPhotoValidator',
				'allowEmpty'=>true,
				'mimeType'=>array('image/jpeg', 'image/png'),
			),
			array('mangaId, title', 'safe', 'on'=>'search'),
			array('id, mangaId', 'required', 'on'=>'insertLanguage'),
		);
	}

	/**
	 * @return array relational rules.
	 */
	public function relations() {
		// NOTE: you may need to adjust the relation name and the related
		// class name for the relations automatically generated below.
		return array(
			'manga'=>array(self::BELONGS_TO, 'Manga', 'mangaId'),
		);
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels() {
		return array(
			'id'=>'Chapter',
			'mangaId'=>'4-Koma',
			'manga.title'=>'4-Koma',
			'volume'=>'Volume',
			'sequence'=>'Chapter',
			'humanSequence'=>'Chapter',
			'title'=>'Title',
			'createdAt'=>'Created At',
			'updatedAt'=>'Updated At',
		);
	}

	/**
	 * Retrieves a list of models based on the current search/filter conditions.
	 * @return CActiveDataProvider the data provider that can return the models
	 * based on the search/filter conditions.
	 */
	public function search() {
		// Warning: Please modify the following code to remove attributes that
		// should not be searched.

		$criteria = new CDbCriteria;
		$criteria->order = 'volume, sequence, subSequence, title';
		$criteria->compare('mangaId', $this->mangaId);
		$criteria->compare('title', $this->title, true);

		return new CActiveDataProvider($this, array('criteria'=>$criteria));
	}

	protected function beforeSave() {
		$this->cover = CUploadedFile::getInstance($this, 'cover');
		if ($this->cover) {
			$this->extension = $this->cover->extensionName;
		}
		return parent::beforeSave();
	}

	protected function afterSave() {
		parent::afterSave();
		if ($this->cover) {
			$this->cover->saveAs($this->coverPath);
			$image = Yii::app()->image->load($this->coverPath);
			$image->resize(150, NULL, 4)->quality(75);
			$image->save($this->coverThumbnailPath);
		}
		$this->manga->save(false);
	}

	public function getCoverPath() {
		$folder = Yii::app()->params['files'] . '/chapters';
		return "{$folder}/{$this->id}.{$this->extension}";
	}

	public function getCoverThumbnailPath() {
		$folder = Yii::app()->params['files'] . '/chapters/_thumbnails';
		return "{$folder}/{$this->id}.jpg";
	}

	public function getCoverUrl() {
		$baseUrl = Yii::app()->request->baseUrl;
		return "$baseUrl/files/chapters/{$this->id}.{$this->extension}";
	}

	public function getCoverThumbnailUrl() {
		$baseUrl = Yii::app()->request->baseUrl;
		return "$baseUrl/files/chapters/_thumbnails/{$this->id}.jpg";
	}

	public function listData() {
		$criteria = new CDbCriteria();
		$criteria->order = 'title';
		$criteria->compare('mangaId', $this->mangaId);
		$criteria->compare('title', $this->title, true);
		$models = self::model()->findAll($criteria);
		return CHtml::listData($models, 'id', 'title');
	}

	public function beforeValidate() {
		$needle = $this->scenario;
		$haystack = array('insert', 'update');
		if (array_search($needle, $haystack) !== false) {
			if (!$this->sequence && !$this->title) {
				$this->addError(
					'sequence', 'Chapter cannot be blank if title is blank'
				);
				$this->addError(
					'title', 'Title cannot be blank if chapter is blank'
				);
			}
		}
		return parent::beforeValidate();
	}

	public function getHumanSequence() {
		if ($this->sequence) {
			return $this->sequence . $this->subSequence;
		} else {
			return '';
		}
	}
	
	public function getSequenceTitle() {
		$sequence = $this->humanSequence;
		$title = $this->title;
		if ($sequence && $title) {
			return $sequence . '. ' . $title;
		} else if ($sequence) {
			return 'Chapter ' . $sequence;
		} else {
			return $title;
		}
	}

}